<?php
// +----------------------------------------------------------------------
// | my
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: $this <498944516@qq.com>
// +----------------------------------------------------------------------
namespace app\rob\model;

use think\Model;
use think\helper\Time;

class RobAnswerLog extends Model
{

    protected $sex = ['未知','男','女'];
    protected $insert = ['status'=>1];  
    
   

    public function info($openid,$field=true){
      
     
      $map['openid']=$openid;
      
      $log = $this->field($field)->where($map)->find();
      
      return  $log;
    }

    public function check($answer,$data){
    
      if ($answer['limit_time']){
        switch ($answer['limit_time']) {
          case 1:
            $limit_time=[time()-3600,time()];
            break;
          case 2:
            $limit_time=Time::today();
            break;
          case 3:
            $limit_time=Time::week();;
            break;
          case 4:
            $limit_time=Time::month();;
            break;
          case 5:
            $limit_time=Time::year();;
            break;
        }
      
      $total=$this->where('create_time','between time',$limit_time)->where('openid',$data['openid'])->where('answer',$answer['id'])->count();
      }else{
      $total=$this->where('openid',$data['openid'])->where('answer',$answer['id'])->count();  
      }

      if ($total>=$answer['limit_times']){
        $last=$this->where('openid',$data['openid'])->where('answer',$answer['id'])->order('create_time desc')->find();
        $error='你已经在'.date('Y-m-d H:i:s',$last['create_time']). '用完了参加'.$answer['title'].'机会';  
        return ['code'=>-1,'error'=>$error?$error:$answer['error']];
      } 
      
      if ($answer['limit_week'] and strstr($answer['limit_week'],date('N'))=='') {
         return ['code'=>-2,'error'=>'每周'.$answer['limit_week'].'开放,敬请关注'];
      }

      if ($answer['limit_sex'] and $answer['limit_sex']!=$data['fans']['sex']) return ['code'=>-3,'error'=>$this->sex[$answer['limit_sex']].'生才能使用哦'];

      if ($answer['limit_type'] and $answer['limit_type']!=$data['MsgType']) return ['code'=>-3,'error'=>'机会已经用光'];
     
      return ['code'=>1];
      
    }

    public function add($data){
      $res = $this->allowField(true)->data($data)->save();
    }
   
}